package com.chhuang.tutool.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.chhuang.tutool.R
import com.chhuang.tutool.databinding.AdapterMessageItemLayoutBinding
import com.chhuang.tutool.modle.MessageBean
import java.text.SimpleDateFormat

class MessageListAdapter(private var messageList: MutableList<MessageBean>): RecyclerView.Adapter<MessageListAdapter.ViewHolder>()  {
    companion object{
        private const val TAG = "MessageListAdapter"
        private val formater = SimpleDateFormat("yyyyMMdd hh:mm:ss")
        private val imageBackgroundDrawable = listOf(
            R.drawable.item_background_lavender,
            R.drawable.item_background_mint)
    }
    inner class ViewHolder(val binding: AdapterMessageItemLayoutBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = AdapterMessageItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        with(holder){
            with(messageList[position]){
                binding.root.setBackgroundResource(imageBackgroundDrawable[if(this.isLocal) 0 else 1])
                binding.ipTextView.text = "${this.ip}:${port}"
                binding.timeTextView.text = formater.format(this.time)
                binding.messageTextView.text = this.message
            }
        }
    }

    override fun getItemCount(): Int {
        return messageList.size
    }

    fun loadOne(message: MessageBean) {
        val len = messageList.size
        messageList.add(message)
        this.notifyItemRangeInserted(len, 1)
    }

    fun loadMore(messages: List<MessageBean>) {
        val len = messageList.size
        messageList.addAll(messages)
        this.notifyItemRangeInserted(len, messages.size)
    }
}